import {CommonTool} from "./js/common.tool.js";

// 上传文件
document.getElementById("file").onclick = function () {
    const input = document.createElement('input');
    input.style.display = 'none';
    input.type = 'file';
    input.setAttribute('multiple', '');
    const event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true); // 这里的click可以换成你想触发的行为
    input.dispatchEvent(event); // 这里的clickME可以换成你想触发行为的DOM结点
    input.onchange = (e) => {
        new Index().stopUpload = false
        new Index().uploadFolderFile(e.currentTarget['files'], "1");
    };
};
let index = 0;


/**
 * 上传文件
 */
export class Index {
    /**
     * 上传文件数据处理
     */
    uploadFolderFile(files, folderId) {
        this.count = 0;
        const array = [];
        for (const file of files) {
            const data = {
                data: {
                    file,
                    folderId,
                    index: 0,
                    url: 0,
                    hashCode: 0,
                    fileIndex: 0,
                    name: file.name,
                    size: file.size,
                    progress: 0,
                },
                stopUpload: false,
                reader: undefined,
                status: ''
            };
            array.push(data);
        }
        array.reverse();
        array.forEach((dataModel, i) => {
            dataModel.data['index'] = i;
            let data = {};
            data = dataModel.data;
            this.getMd5(data, (hashCode) => {
                data.hashCode = hashCode;
                data.url = "/users/1/files";
                this.uploadFile(data);
            });
        });
    }

    /**
     * 获取文件hash值
     * data: { file, folderId, index, url, hashCode, fileIndex }
     */
    getMd5(data, fun, renewalSize) {
        if (!CommonTool.notNull(renewalSize)) {
            renewalSize = 10485760;
        }
        if (!CommonTool.notNull(data.fileIndex)) {
            data.fileIndex = 0;
        }
        const that = this;
        that.updateProgress('load-start', data);
        const file = data.file;
        const reader = new FileReader();
        const spark = new SparkMD5.ArrayBuffer();
        let current = 0;
        reader.readAsArrayBuffer(file.slice(current, current + renewalSize));
        reader.onload = (e) => {
            if (that.verifyStop('load', data, reader)) {
                return false;
            }
            spark.append(e.target['result']);
            if (file.size <= current) {
                const md5 = spark.end();
                that.updateProgress('load-success', data);
                data.fileIndex = 0;
                fun(md5);
            } else {
                current += renewalSize;
                data.fileIndex += renewalSize;
                if (file.size <= current) {
                    current = file.size;
                    data.fileIndex = file.size;
                }
                reader.readAsArrayBuffer(file.slice(current, current + renewalSize));
                if (CommonTool.notNull(current)) {
                    const progress = parseInt((current / (file.size / 100)) + '');
                    that.updateProgress('loading', data, progress);
                }
            }
        };
    }

    /**
     * 上传文件
     * data: { file, folderId, index, url, hashCode, fileIndex }
     */
    uploadFile(data, renewalSize) {
        if (!CommonTool.notNull(renewalSize)) {
            renewalSize = 0;
        }
        let fileIndex = data.fileIndex;
        if (!CommonTool.notNull(fileIndex)) {
            fileIndex = 0;
        }
        const that = this;
        const file = data.file;
        this.updateProgress('upload-start', data);
        // 上传文件
        const formData = new FormData();
        const blob = file.slice(fileIndex, fileIndex + renewalSize);
        formData.append('file', blob);
        formData.append('name', file.name);
        formData.append('hashCode', data.hashCode);
        formData.append('fileIndex', fileIndex);
        formData.append('size', file.size);
        formData.append('folderId', data.folderId);
        let array;
        if (file.webkitRelativePath !== '' && file.webkitRelativePath !== null && file.webkitRelativePath !== undefined) {
            array = file.webkitRelativePath.split('/');
            array.pop();
        } else {
            array = [];
        }
        formData.append('folderNames', array);
        const httpRequest = new XMLHttpRequest();
        httpRequest.open('POST', data.url);
        const token = sessionStorage.getItem("token");
        httpRequest.setRequestHeader('token', token);
        httpRequest.upload.addEventListener('progress', (evt) => {
            if (10485760 >= file.size) {
                const progress = parseInt(Math.round(evt.loaded * 100 / evt.total) + '');
                if (progress === 100) {
                    that.updateProgress('success', data);
                } else {
                    that.updateProgress('uploading', data, progress);
                }
            }
        }, false);
        httpRequest.onloadend = async (e) => {
            if (that.verifyStop('upload', data)) {
                return false;
            }
            if (e.target['status'] === 200) {
                if (e.target['response']) {
                    let res = {fileIndex: 0, finish: false, renewalSize: 0};
                    res = JSON.parse(e.target['response']);
                    if (res.finish) {
                        that.updateProgress('upload-success', data);
                    } else {
                        const progress = parseInt(Math.round(res.fileIndex / file.size * 100) + '');
                        that.updateProgress('uploading', data, progress);
                        data.fileIndex = res.fileIndex;
                        that.uploadFile(data, res.renewalSize);
                    }
                }
            } else if (e.target['status'] === 400) {
                that.updateProgress('upload-fail', data);
                if (e.target['response']) {
                    const ref = JSON.parse(e.target['response']);
                    console.error(ref);
                }
            } else {
                that.updateProgress('upload-fail', data);
            }
            return false;
        };
        httpRequest.send(formData);
    }

    /**
     * 验证是否暂停
     * data: { file, folderId, index, url, hashCode, fileIndex }
     */
    verifyStop(type, data, reader) {
        if (this.stopUpload) {
            if (type === 'load') {
                data['reader'] = reader;
            }
            return true;
        }
        return false;
    }

    /**
     * 更新进度
     *  type 类型
     * data: { file, folderId, index, url, hashCode, fileIndex }
     */
    updateProgress(type, data, value) {
        if (type === 'upload-fail') { // 上传失败
            console.log("上传失败")
        } else if (type === 'upload-success') { // 上传成功;
            index++;
            document.getElementById("progress").innerText = index;
            console.log("上传成功")
        } else if (type === 'uploading') { // 上传中
            console.log("上传中")
        } else if (type === 'upload-start') { // 上传开始
            console.log("上传开始")
        } else if (type === 'load-start') { // 加载开始
            console.log("加载开始")
        } else if (type === 'loading') { // 加载中
            console.log("加载中")
        } else if (type === 'load-success') { // 加载完成
            console.log("加载完成")
        }
    }

}


